package com.hy.example.shared.distribute.rate;

import com.google.common.util.concurrent.RateLimiter;
import lombok.RequiredArgsConstructor;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class StandaloneRateLimiter implements DistRateLimiter {
    private final RateLimiter rateLimiter;

    public static DistRateLimiter create() {
        return new StandaloneRateLimiter(RateLimiter.create(1));
    }

    @Override
    public void trySetRate(long rateInInterval, long rateIntervalSecond) {
        rateLimiter.setRate(rateInInterval * 1.0 / rateIntervalSecond);
    }

    @Override
    public boolean tryAcquire() {
        return rateLimiter.tryAcquire();
    }

    @Override
    public boolean tryAcquire(int permits) {
        return rateLimiter.tryAcquire(permits);
    }

    @Override
    public void acquire() {
        rateLimiter.acquire();
    }

    @Override
    public void acquire(int permits) {
        rateLimiter.acquire(permits);
    }

    @Override
    public boolean tryAcquire(long timeout, TimeUnit unit) {
        return rateLimiter.tryAcquire(timeout, unit);
    }

    @Override
    public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
        return rateLimiter.tryAcquire(permits, timeout, unit);
    }
}
